package com.sps.tuya_plugin;

import androidx.annotation.NonNull;

import android.app.Application;
import android.os.Handler;
import android.os.Message;

import java.util.HashMap;
import java.util.Map;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

import com.tuya.iotapp.activator.builder.ActivatorBuilder;
import com.tuya.iotapp.activator.config.IEZActivator;
import com.tuya.iotapp.activator.config.TYActivatorManager;

import android.widget.Toast;



/**
 * TuyaPlugin
 */
public class TuyaPlugin implements FlutterPlugin, MethodCallHandler {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity

    private MethodChannel channel;

    static int ERROR_CODE_TYPE_ERROR = -100; // 数据类型类型错误
    static int ERROR_CODE_NOT_LOGIN = -101; // 还未登录
    static int ERROR_CODE_PARAMS_ERROR = -502; // 参数错误
    static int SUCCESS_CODE = 200; // 执行成功

    protected android.content.Context mContext;
    private MethodChannel.Result result;
    private IEZActivator mEzConfig;

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        this.mContext = flutterPluginBinding.getApplicationContext();
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "tuya_plugin");
        channel.setMethodCallHandler(this);
      
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
        this.result = result;
        System.out.println("onMethodCall" + call.method);
        switch (call.method) {
            case "set_ec_net":
                this.setEC(call.argument("ssid").toString(), call.argument("password").toString(), call.argument("region").toString(),call.argument("token").toString(),call.argument("secret").toString());
                break;
            case "set_ap_net":
                this.setAP(call.argument("ssid").toString(), call.argument("password").toString(), call.argument("token").toString());
                break;
            case "destroy":
                System.out.println("销毁涂鸦插件实例");
                break;
            case "stopAP":
                this.stopAP();
            default:
                result.success("Android " + android.os.Build.VERSION.RELEASE);
                break;
        }
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
    }

    // 快连（EZ）模式
    public void setEC(String ssid, String password, String region,String token,String secret) {
        try {
            mEzConfig = TYActivatorManager.newEZActivator(new ActivatorBuilder(mContext,
                    ssid,
                    password,
                    region,
                    token,
                    secret));
            mEzConfig.start();
            System.out.println("开始快连（EZ）模式配网");
            callResult(SUCCESS_CODE,"EZ");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 热点（AP）模式
    public void setAP(String ssid, String password, String token) {
//        System.out.println("开始快连（AP）模式配网");
//        mModelEnum = TY_AP;
//        mTuyaActivator = TuyaHomeSdk.getActivatorInstance().newActivator(new ActivatorBuilder()
//                .setSsid(ssid)
//                .setContext(mContext)
//                .setPassword(password)
//                .setActivatorModel(TY_AP)
//                .setTimeOut(CONFIG_TIME_OUT)
//                .setToken(token).setListener(new ITuyaSmartActivatorListener() {
//                    @Override
//                    public void onError(String error, String s1) {
//                        //                resultError(WHAT_AP_ACTIVE_ERROR, error, s1);
//                        System.out.println("AP配网失败");
//                        System.out.println(error);
//                        callResult(WHAT_AP_ACTIVE_ERROR, error);
//                    }
//
//                    @Override
//                    public void onActiveSuccess(DeviceBean gwDevResp) {
//                        //                resultSuccess(WHAT_AP_ACTIVE_SUCCESS, gwDevResp);
//                        System.out.println("AP配网成功");
//                        callResult(WHAT_AP_ACTIVE_SUCCESS, gwDevResp.getDevId());
//                    }
//
//                    @Override
//                    public void onStep(String step, Object o) {
//                        switch (step) {
//                            case ActivatorAPStepCode.DEVICE_BIND_SUCCESS:
//                                //                    resultSuccess(WHAT_BIND_DEVICE_SUCCESS, o);
//                                System.out.println("AP配网设备绑定成功");
//                                callResult(WHAT_AP_ACTIVE_SUCCESS, "WHAT_BIND_DEVICE_SUCCESS");
//                                break;
//                            case ActivatorAPStepCode.DEVICE_FIND:
//                                //                    resultSuccess(WHAT_DEVICE_FIND, o);
//                                System.out.println("AP配网发现设备");
//                                callResult(WHAT_DEVICE_FIND, "WHAT_DEVICE_FIND");
//
//                                break;
//                        }
//                    }
//                }));
//
//        mTuyaActivator.start();

    }

    // 停止（AP）模式配网
    public void stopAP() {
        System.out.println("停止EZ配网");
        try {
            mEzConfig.stop();
            // stopLoop();
        } catch (Exception e) {

        }

    }

    ////////////////////辅助方法//////////////////
    /*
     * 传递消息给Flutter层
     * */
    public void callResult(int code, String msg) {
        try {
            HashMap<String, String> map = new HashMap<>();
            map.put("code", String.format("%d", code));
            map.put("msg", msg);

            Message message = Message.obtain();
            message.obj = map;
            result.success(map);
        } catch (Exception e) {

        }
    }

    /*
     * 传递带data的消息给Flutter层
     * */
    // public void callResult(int code, String msg, String data) {
    //     HashMap<String, String> map = new HashMap<>();
    //     map.put("code", String.format("%d", code));
    //     map.put("msg", msg);
    //     map.put("data", data);

    //     Message message = Message.obtain();
    //     message.obj = map;
    //     result.success(map);
    // }
}
